<template>
  <!-- 页面-单据序列管理-设置 -->
  <div class="run-mod-box innerPageTable-box-Four ReceiptSequenceRule-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="flexFieldForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 单据序列编码 -->
          <Form-item prop="receiptSeqCode" :label="$t('module.receiptSequence.receiptSeqCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model="searchForm.receiptSeqCode"
              :placeholder="$t('module.receiptSequence.enterReceiptSeqCode')"
              disabled
            />
          </Form-item>

          <!-- 单据序列名称 -->
          <Form-item prop="receiptSeqName" :label="$t('module.receiptSequence.receiptSeqName')">
            <Input
              type="text"
              :maxlength="30"
              v-model="searchForm.receiptSeqName"
              :placeholder="$t('module.receiptSequence.enterReceiptSeqName')"
              disabled
            ></Input>
          </Form-item>

          <!-- <Form-item prop="resetFrequency" :label="$t('module.receiptSequence.resetFrequency')">
                <Input type="text" :maxlength="30" v-model="searchForm.resetFrequency" :placeholder="$t('module.receiptSequence.enterReceiptSeqName')" readonly ></Input>
          </Form-item>-->
          <!-- 重置频率 -->
          <Form-item prop="resetFrequency" :label="$t('module.receiptSequence.resetFrequency')">
            <Select style="width:150px" v-model="searchForm.resetFrequency" disabled>
              <Option :title="$t('module.receiptSequence.resetFrequencyOption.everyDay')" value="DAILY" key="DAILY">{{
                $t('module.receiptSequence.resetFrequencyOption.everyDay')
              }}</Option>
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.everyMonth')"
                value="MONTHLY"
                key="MONTHLY"
                >{{ $t('module.receiptSequence.resetFrequencyOption.everyMonth') }}</Option
              >
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.everyYear')"
                value="YEARLY"
                key="YEARLY"
                >{{ $t('module.receiptSequence.resetFrequencyOption.everyYear') }}</Option
              >
              <Option :title="$t('module.receiptSequence.resetFrequencyOption.never')" value="NEVER" key="NEVER">{{
                $t('module.receiptSequence.resetFrequencyOption.never')
              }}</Option>
            </Select>
          </Form-item>

          <!-- 应用效果 -->
          <Form-item prop="receiptSeqName" label="" class="inputPosition">
            <RPButton
              optType="reset"
              slot="label"
              @click.native="applyResult"
              :text="$t('module.receiptSequence.applyResult')"
              style="borderRadius:0;width:100%;"
            />
            <!-- <Button slot="label"  class= 'apply-button' @click="applyResult">{{$t('module.receiptSequence.applyResult')}}</Button> -->
            <Input disabled type="text" :maxlength="30" v-model="searchForm.applyResult" width="150px"></Input>
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>

    <InnerPageTable ref="ruleTable" :config="pageTableConfig">
      <div slot="table-bar">
        <RPButton optType="create" @click="addOrUpdate()" />
        <RPButton optType="batch" @click="deleted()" />
      </div>
    </InnerPageTable>
  </div>
</template>
<script>
import ReceiptSequenceRuleEdit from './ReceiptSequenceRuleEdit.vue'
import role from '@lang/modules/role'
import valueSet from '@lang/modules/valueSet'
import receiptSequence from '@lang/modules/receiptSequence'
import userManage from '@lang/modules/userManage'
import { GetValueSetByCode } from './common.js'
import ReceiptSequenceInputParameter from './ReceiptSequenceInputParameter.vue'

export default {
  components: { ReceiptSequenceRuleEdit, ReceiptSequenceInputParameter },
  locales: {
    'zh-CN': {
      module: {
        receiptSequence: receiptSequence['zh-CN'],
        role: role['zh-CN'],
        valueSet: valueSet['zh-CN'],
        userManage: userManage['zh-CN']
      }
    },
    'en-US': {
      module: {
        receiptSequence: receiptSequence['en-US'],
        role: role['en-US'],
        valueSet: valueSet['en-US'],
        userManage: userManage['en-US']
      }
    }
  },
  props: {
    obj: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    let _obj = this.obj
    return {
      pageTableConfig: {
        loadDataFn: this.GetReceiptSequenceRuleList,
        columnsFn: this.columns,
        initParam: {
          receiptSeqCode: _obj.receiptSeqCode
        },
        isPage: false
      },
      searchForm: {
        receiptSeqCode: _obj.receiptSeqCode,
        receiptSeqName: _obj.receiptSeqName,
        resetFrequency: _obj.resetFrequency,
        applyResult: ''
      },
      segmentList: [],
      effect: '',
      parameter: [],
      sequence: {
        paramObj: {},
        receiptSeqCode: _obj.receiptSeqCode,
        isAvailable: _obj.isAvailable
      }
    }
  },
  // computed: {},
  // beforeMount: function() {},
  // mounted: function() {},
  // beforeDestroy: function() {},
  // destroyed: function() {},
  created: function() {
    this.init()
  },
  mounted: function() {
    // this.search();
  },
  methods: {
    // 获取所有段字段的值，用来将表格的段字段key转为value
    init() {
      GetValueSetByCode({ code: 'RULE_SEGMENT' }).then(response => {
        this.segmentList = response
        this.search()
      })
    },
    // 获取表格列表数据
    GetReceiptSequenceRuleList: function({ responseProcess, param }) {
      return $http.post(`${window.RPConfig.setting}/sys/receiptSeq/rule/query`, param).then(response => {
        let resData = response.data
        // 状态为有效：禁用复选框，不可删除
        resData = this.$root.$options.filters['selection-disabled'](resData)
        this.parameter = resData
        resData.forEach(item => {
          item.ruleSegmentField = this.getRuleSegmentField(item.ruleSegmentField)
          if (item.ruleSegmentField == '参数') {
            this.effect = item.ruleSegmentField
          }
        })
        //适配结构
        response = {
          recordList: response.data
        }
        responseProcess(response)
      })
    },
    // 把段字段的数据的key英文转成需显示的value中文
    getRuleSegmentField(ruleSegmentField) {
      if (ruleSegmentField) {
        let _ruleSegmentField = this.segmentList.find(item => item.vsiKey == ruleSegmentField) || {}
        return _ruleSegmentField.vsiValue
      }
    },
    columns() {
      const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
      return [
        {
          type: 'selection',
          width: 45
          // fixed: 'left',
          // type: 'index',
        },
        {
          title: this.$t('common.num'),
          key: 'ruleSegmentOrder',
          align: 'center',
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_2_WORDS,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_2_WORDS + COLUMN_WIDTH.MAX_WIDTH_MORE,

        },
        {
          title: this.$t('module.receiptSequence.field'),
          key: 'ruleSegmentField',
          // sortable: "custom",
          align: 'center',
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_4_WORDS,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_4_WORDS + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.ruleSegmentField
                }
              },
              params.row.ruleSegmentField
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.fieldValue'),
          key: 'ruleSegmentFieldValue',
          // sortable: "custom",
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.ruleSegmentFieldValue
                }
              },
              params.row.ruleSegmentFieldValue
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.dateFormat'),
          key: 'datePattern',
          align: 'center',
          minWidth: COLUMN_WIDTH.COLUMN_WIDTH_YYYYMMDD,
          maxWidth: COLUMN_WIDTH.COLUMN_WIDTH_YYYYMMDD + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.datePattern
                }
              },
              params.row.datePattern
            )
          }
        },

        {
          title: this.$t('module.receiptSequence.digit'),
          key: 'seqLength',
          // sortable: "custom",
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.seqLength
                }
              },
              params.row.seqLength
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.stepSize'),
          key: 'seqIncrement',
          // sortable: "custom",
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.seqIncrement
                }
              },
              params.row.seqIncrement
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.startValue'),
          key: 'seqStartValue',
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.seqStartValue
                }
              },
              params.row.seqStartValue
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.parameterCode'),
          key: 'paramCode',
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.paramCode
                }
              },
              params.row.paramCode
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.parameterName'),
          key: 'paramName',
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.paramName
                }
              },
              params.row.paramName
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.parameterDefault'),
          key: 'paramDefaultValue',
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.paramDefaultValue
                }
              },
              params.row.paramDefaultValue
            )
          }
        },
        {
          title: this.$t('common.status'),
          key: 'enabled',
          align: 'center',
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,
          render: (h, params) => {
            return h(
              'StatusButton',
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },

                props: {
                  status: params.row.enabled == 1 ? '0' : '1'
                }
              },
              params.row.enabled == 1 ? this.$t('common.enable') : this.$t('common.disable')
            )
          }
        },
        {
          title: this.$t('common.operating'),
          align: 'left',
          fixed: 'right',
          width: 80,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'icon',
                    icon: 'md-create',
                    text: this.$t('common.edit'),
                    handle: () => {
                      this.addOrUpdate(params.row.id)
                    }
                  },
                  {
                    type: 'icon',
                    icon: 'ios-trash',
                    text: this.$t('common.delete'),
                    hidden: params.row.enabled == 1,
                    handle: () => {
                      this.deleted(params.row.id)
                    }
                  }
                ]
              }
            })
          }
        }
      ]
    },
    addOrUpdate(ruleId) {
      const { $refs, refKeys } = this.$refs['ruleTable']
      new this.$pageModal(
        ReceiptSequenceRuleEdit,
        {
          props: {
            existingData: $refs[refKeys.table].data,
            ruleId: ruleId,
            receiptSeqCode: this.obj.receiptSeqCode
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    deleted(id) {
      // let itemIds = this.getIds();
      let itemIds
      if (id) {
        itemIds = [id]
      } else {
        itemIds = this.getIds()
      }
      if (!itemIds || itemIds == undefined || itemIds == '') {
        this.$message.error(this.$t('module.receiptSequence.selctItems'))
        return
      }
      new $confirm(this.$t('module.receiptSequence.confirmToDelete'), this).then(() => {
        $http.post(`${window.RPConfig.setting}/sys/receiptSeq/rule/delete?ids=${itemIds}`, itemIds).then(() => {
          this.$message.success({
            content: this.$t('module.receiptSequence.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
      })
    },
    getIds() {
      let selectedItems = this.$refs['ruleTable'].getSelectioned() || []
      let ids = []
      for (let item of selectedItems) {
        ids.push(item.id)
      }
      return ids
    },
    applyResult() {
      if (this.effect) {
        new this.$pageModal(
          ReceiptSequenceInputParameter,
          {
            props: {
              parameter: this.parameter,
              objReceiptSeqCode: this.obj
            }
          },
          data => {
            this.searchForm.applyResult = data
          }
        )
      } else {
        $http.post(`${window.RPConfig.setting}/sys/receiptSeq/apply`, this.sequence).then(response => {
          console.log('resdf', response)
          if (response.status == 200) {
            this.searchForm.applyResult = response.data
          } else {
            this.$message.error({
              content: response.statusText,
              duration: 3
            })
          }
        })
      }
    },
    search(page) {
      this.$refs['ruleTable'].load(this.searchForm, page)
      this.searchForm.applyResult = ''
    }
  },
  watch: {},
  directives: {}
}
</script>
<style lang="less">
.inputPosition .ivu-input[disabled] {
  border: 0;
}
// ok注释的样式
// .ReceiptSequenceRule-page {
//   .apply-button{
//     position: absolute;
//     top: calc(~"50% + 5px");
//     transform: translateY(-50%);
//   }
// }
</style>
